
package com.oa.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.common.annotation.SysLog;
import com.oa.common.utils.*;
import com.oa.common.validator.Assert;
import com.oa.common.validator.ValidatorUtils;
import com.oa.common.validator.group.AddGroup;
import com.oa.common.validator.group.UpdateGroup;
import com.oa.modules.sys.entity.SysRoleEntity;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.entity.SysUserRoleEntity;
import com.oa.modules.sys.form.PasswordForm;
import com.oa.modules.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.*;

/**
 * 系统用户
 *
 * @author sunhui
 */
@RestController
@Api(tags = "用户相关接口")
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 所有用户列表
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            if (getUser().getRoleIdList().get(0) != Constant.ADMIN) {
                //params.put("tenantId", getTenantId());
            } else {
                params.put("createUserId", getUserId());
            }
        }
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    @PostMapping("/findByMobile")
    public R findById(@RequestBody Map<String, Object> params){
        String mobile = (String) params.get("mobile");
        String name = (String) params.get("name");
        String idCard = (String) params.get("idCard");
        SysUserEntity sysUser = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("mobile", mobile));
        if (Objects.nonNull(sysUser)) {
            SysUserRoleEntity sysUserRoleEntity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>().eq("user_id", sysUser.getUserId()));
            sysUser.setRoleId(sysUserRoleEntity.getRoleId());
            sysUser.setUsername(Base64.getEncoder().encodeToString(sysUser.getUsername().getBytes()));
            sysUser.setMobile(Base64.getEncoder().encodeToString(sysUser.getMobile().getBytes()));
            sysUser.setName(Base64.getEncoder().encodeToString(sysUser.getName().getBytes()));
            return R.ok().put("data", sysUser);
        } else {
            SysUserEntity userEntity = new SysUserEntity();
            userEntity.setUsername(name);
            userEntity.setName(name);
            userEntity.setMobile(mobile);
            userEntity.setIdCard(idCard);
            userEntity.setCreateTime(new Date());
            sysUserService.save(userEntity);
            SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
            sysUserRole.setUserId(userEntity.getUserId());
            sysUserRole.setRoleId(9L);
            sysUserRoleService.save(sysUserRole);
            userEntity.setRoleId(sysUserRole.getRoleId());
            userEntity.setUsername(Base64.getEncoder().encodeToString(userEntity.getUsername().getBytes()));
            userEntity.setMobile(Base64.getEncoder().encodeToString(userEntity.getMobile().getBytes()));
            userEntity.setName(Base64.getEncoder().encodeToString(userEntity.getName().getBytes()));
            return R.ok().put("data", userEntity);
        }

    }


    /**
     * 获取某个身份的用户列表
     */
    @PostMapping("/getOperator")
    public R getOperator() {
        List<SysUserEntity> operator = sysUserService.getOperator("8");
        for (int i = 0; i < operator.size(); i++) {
            List<Long> roleIdList = sysUserRoleService.queryRoleIdList(operator.get(i).getUserId());
            operator.get(i).setRoleIdList(roleIdList);
        }
        return R.ok().put("operator", operator);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        String password = form.getPassword();
        String newPassword = form.getNewPassword();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @PostMapping("/info/{userId}")
    @ApiOperation(value = "用户信息")
    //@RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        List<SysRoleEntity> roleList = new ArrayList<SysRoleEntity>();
        roleIdList.forEach(data -> {
            roleList.add(sysRoleService.getById(data));
        });
        user.setRoleList(roleList);
        //if (StringUtils.isBlank(user.getDeptId())) {
        //    user.getTTenantMainEntity().setTenantName("暂无企业,请联系管理员进行分配");
        //} else {
        //    user.setTTenantMainEntity(tTenantMainService.getById(sysDeptService.getById(user.getDeptId()).getTenantId()));
        //}

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    //@RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
        user.setCreateUserId(getUserId());
        sysUserService.saveUser(user);
        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping(value = "/update")
    @ApiOperation(value = "修改用户信息")
    public R update(@RequestBody SysUserEntity user) throws IllegalStateException, IOException {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        if (StringUtils.isBlank(user.getUserId() + "")) {
            return R.error("缺失必传参数");
        }
        user.setUpdateTime(new Date());
        sysUserService.update(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /**
     * 根据id查询用户列表
     *
     * @return
     */
    @PostMapping("/qryUserListByIds")
    @ApiOperation(value = "根据id查询用户列表")
    public R qryUserListByIds(@RequestBody SysUserEntity user) {
        List<Map> list = new ArrayList<>();
        if (user.getUserIds().length < 1) {
            return R.error("至少传入一个用户id");
        }

        for (int i = 0; i < user.getUserIds().length; i++) {
            QueryWrapper wra = new QueryWrapper<>().eq("user_id", user.getUserIds()[i]);
            Map usersMap = sysUserService.getMap(wra);
            SysRoleEntity role = new SysRoleEntity();
            // 根据用户id查询角色
            List<SysUserRoleEntity> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRoleEntity>().eq("user_id", usersMap.get("user_id")));
            if (userRoleList != null && userRoleList.size() > 0) {
                List roleList = new ArrayList();
                userRoleList.forEach(data -> {
                    role.setRoleId(data.getRoleId());
                    SysRoleEntity roles = sysRoleService.getById(role);
                    roleList.add(roles);
                });
                usersMap.put("role", roleList);
            }
            list.add(usersMap);
        }
        return R.ok().put("list", list);
    }

    /**
     * 查询用户列表
     *
     * @return
     */
    @PostMapping("/qryUserList")
    @ApiOperation(value = "查询用户列表")
    public R qryUserList(@RequestBody Map<String, Object> user) {
//        Map<String, Object> params = new HashMap<>();
//        params.put("deptId", user.getDeptId());
        PageUtils list = sysUserService.auditUserList(user);
//        PageUtils page = sysUserService.queryPage(user);
        return R.ok().put("page", list);
    }

    @PostMapping(value = "/saveUserInfo")
    @ApiOperation(value = "用户信息添加")
    public R saveUserInfo(@RequestBody SysUserEntity user) throws IllegalStateException, IOException {
        if (StringUtils.isBlank(user.getUsername())) {
            return R.error("缺失必传参数");
        }
        if (StringUtils.isEmpty(user.getWxOpenId())) {
            SysUserEntity u = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("username", user.getUsername()));
            if (u != null) {
                return R.error("用户已存在");
            }
            ValidatorUtils.validateEntity(user, UpdateGroup.class);
        } else {
            SysUserEntity u = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("wx_open_id", user.getWxOpenId()));
            if (u != null) {
                return R.error("用户已存在");
            }
        }
        // 将数据储存到数据库中
        user.setCreateTime(new Date());
//        user.setCreateUserId(getUserId());
        sysUserService.save(user);
        Long id = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("username", user.getUsername())).getUserId();
        if (user.getRoleIdList() != null && user.getRoleIdList().size() != 0) {
            SysUserRoleEntity userRole = new SysUserRoleEntity();
            userRole.setUserId(id);
            userRole.setRoleId(user.getRoleIdList().get(0));
            sysUserRoleService.save(userRole);
        }
        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/updateInfo")
    @ApiOperation(value = "修改用户")
    @RequiresPermissions("sys:user:update")
    public R updateInfo(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 验证用户名是否唯一
     *
     * @param user
     * @return
     */
    @PostMapping("/checkUserName")
    @ApiOperation(value = "验证用户名是否唯一")
    public R checkUserName(@RequestBody SysUserEntity user) {
        if (StringUtils.isBlank(user.getUsername())) {
            return R.error("必须填写用户名");
        }

        List<SysUserEntity> checkUser = sysUserService.list(new QueryWrapper<SysUserEntity>().eq("username", user.getUsername()));
        if (checkUser.size() > 0) {
            return R.error("用户名已存在!");
        } else {
            return R.ok();
        }
    }

    /**
     * 分配部门
     *
     * @param user
     * @return
     */
    @PostMapping("/sortDept")
    @ApiOperation(value = "分配部门")
    public R sortDept(@RequestBody SysUserEntity user) {

        if (user.getUserIds().length <= 0 || StringUtils.isBlank(user.getDeptId())) {
            return R.error("缺失必传参数");
        }

        for (int i = 0; i < user.getUserIds().length; i++) {
            SysUserEntity data = new SysUserEntity();
            data.setUserId(Long.valueOf(user.getUserIds()[i]));
            data.setDeptId(user.getDeptId());
            sysUserService.updateById(data);
        }

        return R.ok();
    }
}
